package com.Team7.controller;
import com.Team7.call.*;
import com.Team7.domain.Item;
import com.Team7.domain.OFFile;
import com.Team7.domain.Pointer;
import com.Team7.domain.SearchedFile;
import com.Team7.factory.DiskFactory;
import com.Team7.util.DiskUtil;
import com.Team7.util.FileUtil;
import com.Team7.util.StringUtil;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.List;

/**
 * @author lts
 * @CreateTime 2019年11月29日21:58:58
 *              盘古开天地界面
 * */
public class MainController implements  AddFileCall, AddMenuCall, UpdateFileAttrCall,FileTextCall {
    private Stage stage;
    private int i=0;
    private int j=0;
    private int MaxView=0;//界面数 不超过5个
    @FXML
    private TextField tf_path;//路径

    @FXML
    private Button btn_enter;//回车

    @FXML
    private Button btn_C_disk;//c盘

    @FXML
    private Button btn_diskspace;//磁盘空间

    @FXML
    private Button btn_back;//返回


    @FXML
    private AnchorPane mainpane;//放置文件 目录的面板


    @FXML
    private GridPane gridpane;// 9宫格面板


    public MainController(){
        stage=new Stage();
        try {
            FXMLLoader loader=  new FXMLLoader(getClass().getResource("../fxml/Main.fxml"));
            loader.setController(this);
            Scene scene=new Scene(loader.load(),700,500);
            stage.setScene(scene);
            stage.setTitle("磁盘文件管理系统");

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void show() {
        stage.show();
    }


    @FXML
    private void initialize(){

        ContextMenu contextMenu=new ContextMenu();
        MenuItem addFile=new MenuItem("addFile");
        MenuItem addMenu=new MenuItem("addMenu");
        //按了添加文件
        addFile.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                createFileController();
            }
        });

        //按了添加目录
        addMenu.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                createMenuController();
            }
        });

        contextMenu.getItems().addAll(addMenu,addFile);

        ///-------------------------------以下是fxml文件初始化组件---------------------------------------------------------////

        gridpane.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if(event.getButton()==MouseButton.SECONDARY){
                    contextMenu.show(gridpane,event.getScreenX(),event.getScreenY());
                }else{
                    contextMenu.hide();
                }
            }
        });

        btn_diskspace.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                createDiskSpaceController();
            }
        });

        btn_back.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                findBack(btn_back);
            }
        });


    }



    ///-------------------------------以下创建新界面---------------------------------------------------------////

    private void createDiskSpaceController(){
        DiskSpaceController diskSpaceController=new DiskSpaceController(this);
        diskSpaceController.show();
    }

    private void createFileController(){
        String curPath=tf_path.getText().trim();
        System.out.println(curPath);
        FileController fileController=new FileController( this,curPath);
        fileController.show();;
    }

    private void createMenuController(){

        String curPath=tf_path.getText().trim();
        System.out.println(curPath);
       MenuController menuController=new MenuController(this,curPath);
       menuController.show();
    }

    private void createFileAttrController(String path,String name)
    {
        FileAttrController fileAttrController=new FileAttrController(this,path,name);
        fileAttrController.show();
    }

    private void createFileTextController(OFFile ofFile){

        FileTextController fileTextController=new FileTextController(this,ofFile);
        fileTextController.show();

    }

    ///----------------------------------------------------------------------------------------////
    ///----------------------------------------------------------------------------------------////
    ///----------------------------------------------------------------------------------------////
    ///----------------------------------------------------------------------------------------////


    //使用接口返回数据
    @Override
    public void addFile(String filename) {
        System.out.println(filename);
        createFile(filename);
    }

    @Override
    public void addMenu(String filename) {
        System.out.println(filename);
        createMenu(filename);
    }

    @Override
    public void updateFileAttr(Item item) {

    }

    @Override
    public void getStatus(String info) {
        MaxView--;
        System.out.println(info+" "+MaxView);
    }
    ///----------------------------------------------------------------------------------------////
    ///----------------------------------------------------------------------------------------////
    ///----------------------------------------------------------------------------------------////
    ///----------------------------------------------------------------------------------------////


    //刷新 GridPane
    public void refresh( List<Item> itemList){
        //先删除
        gridpane.getChildren().clear();

        //更新
        int p=0;//len是itemList长度
        i=0;j=0;
        while(p<itemList.size()){

            byte[] name=new byte[3];
            for(int i=0;i<3;i++){
                name[i]=itemList.get(p).getAttr()[i];
            }
            String filename=new String(name);
            //文件夹
            if(itemList.get(p).getAttr()[5]==8){
                createMenu(filename);
            }else{//文件
                createFile(filename);
            }
            p++;
        }

    }


    private void createMenu(String fileName){
        //图片
        Image image=new Image(getClass().getResourceAsStream("/images/file.png"),45,45,false,false);
        Button button=new Button();
        button.setGraphic(new ImageView(image));

        //名字
        button.setText(fileName);
        button.setContentDisplay(ContentDisplay.TOP);

        ContextMenu tempMenu=new ContextMenu();
        MenuItem openMenu=new MenuItem("打开");
        openMenu.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //打开目录 将路径传给递归算法 找出对应的子目录 并刷新界面
               openMenu(button);
            }
        });


        MenuItem deleteMenu=new MenuItem("删除");
        deleteMenu.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //删除
                deleteFileMenu(button);
            }
        });

        tempMenu.getItems().addAll(openMenu,deleteMenu);
        button.setContextMenu(tempMenu);

        button.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if(event.getClickCount()==2){
                    openMenu(button);
                }else if(event.getButton()==MouseButton.SECONDARY){
                    tempMenu.show(button,event.getScreenX(),event.getScreenY());
                }else{
                    tempMenu.hide();
                }
            }
        });
        gridpane.add(button,j++,i);
        newLine();

    }

    private void createFile(String fileName){
        //图片
        Image image=new Image(getClass().getResourceAsStream("/images/txt.png"),45,45,false,false);
        Button button=new Button();
        button.setGraphic(new ImageView(image));
        //名字
        button.setText(fileName);
        button.setContentDisplay(ContentDisplay.TOP);


        ContextMenu tempMenu=new ContextMenu();
        //打开文件
        MenuItem openFile=new MenuItem("打开");
        openFile.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //弹出新窗口

                if(MaxView<5){
                    MaxView++;
                    openFile(button);
                    System.out.println("打开文件");
                }else{
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setTitle("Warning Dialog");
                    alert.setHeaderText("You have opened 5 window, please close them before you operate");
                    alert.showAndWait();
                }
            }
        });

        //删除文件
        MenuItem deleteFile=new MenuItem("删除");
        deleteFile.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //更改路径 递归得出子目录 并且更新界面refresh();
                deleteFileMenu(button);
            }
        });

        //修改属性
        MenuItem alterAttr=new MenuItem("属性");
        alterAttr.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //调用 文件属性界面
                System.out.println(tf_path.getText()+button.getText());
                createFileAttrController(tf_path.getText(),button.getText());
                System.out.println("打开属性");;
            }
        });

        //初始化button
        tempMenu.getItems().addAll(openFile,deleteFile,alterAttr);
        button.setContextMenu(tempMenu);

        button.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if(event.getClickCount()==2){
                  openFile(button);
                } else if(event.getButton()==MouseButton.SECONDARY){
                    tempMenu.show(button,event.getScreenX(),event.getScreenY());
                }else{
                    tempMenu.hide();
                }
            }
        });

        gridpane.add(button,j++,i);
        newLine();
    }


    private void openFile(Button button){
        OFFile ofFile=new OFFile();
        String curPath=tf_path.getText().trim();
        String filename=button.getText();
        String absolatePath= StringUtil.getAbsolutePath(curPath,filename);

        SearchedFile searchedFile=FileUtil.findPathSearchedFile(DiskFactory.getDisk(),absolatePath);

        //SearchedFile searchedFile=FileUtil.findFile(absolatePath,DiskFactory.getDisk());

        //private String name;    //绝对路径
        ofFile.setName(absolatePath);
        //private Byte attribute; //文件属性
        ofFile.setAttribute(searchedFile.getItem().getAttr()[5]);
        //private Integer number; //文件起始盘号
        ofFile.setNumber((int) searchedFile.getItem().getAttr()[6]);
        //private Integer length; //文件长度
        ofFile.setLength((int) searchedFile.getItem().getAttr()[7]);
        //private Integer flag;   //操作类型 用“0”表示以读操作方式打开文件，用“1”表示以写操作方式打开文件
        //只能读
        if(searchedFile.getItem().getAttr()[5]%2==1){//只读
            ofFile.setFlag(0);
        }else{
            ofFile.setFlag(1);
        }
        //private Pointer read;   //读文件的位置，文件打开时 dnum 为文件起始盘块号，bnum 为“0”
        Pointer reader=new Pointer();
        reader.setDnum((int) searchedFile.getItem().getAttr()[6]);
        reader.setBnum(0);

        //private Pointer write;  //写文件的位置，文件刚建立时 dnum 为文件起始盘块号，bnum 为“0 ，打开文件时 dnum 和 bnum 为文件的末尾位置
        Pointer writer=FileUtil.getWirterPoniter(DiskFactory.getDisk(),searchedFile);

        ofFile.setRead(reader);
        ofFile.setWrite(writer);

        createFileTextController(ofFile);
    }


    private void findBack(Button button){
        String curPath=tf_path.getText().trim();
        String [] items=curPath.split("/");
        if(items.length==1){
            //donothiing
        }else{
            List<Item> list = null;
            if(items.length==2){
                curPath="C:/";
                list=FileUtil.getFileItem(DiskFactory.getDisk(),2);
            }else{
                curPath=curPath.substring(0,curPath.length()-items[items.length-1].length()-1);
                SearchedFile searchedFile=FileUtil.findPathSearchedFile(DiskFactory.getDisk(),curPath);

                //SearchedFile searchedFile=FileUtil.findFile(curPath,DiskFactory.getDisk());

                list=FileUtil.getFileItem(DiskFactory.getDisk(),searchedFile.getItem().getAttr()[6]);
            }
            tf_path.setText(curPath);
            //查询
            refresh(list);
        }



    }

    private void openMenu(Button button){
        //打开目录 将路径传给递归算法 找出对应的子目录 并刷新界面
        String curPath=tf_path.getText().trim();
        String filename=button.getText();
        String absoluatePath;
        if(curPath.equals("C:/")){
            absoluatePath=curPath+filename;
        }else{
            absoluatePath=curPath+"/"+filename;
        }

        //得到绝对路径 所指向的 行 列
        SearchedFile searchedFile =FileUtil.findPathSearchedFile(DiskFactory.getDisk(),absoluatePath);
        //SearchedFile searchedFile =FileUtil.findFile(absoluatePath,DiskFactory.getDisk());

        //得到当前选中文件的的属性 并且遍历其下面的目录输出
        System.out.println(searchedFile);
        List<Item> list=FileUtil.getFileItem(DiskFactory.getDisk(),searchedFile.getItem().getAttr()[6]);;
        //更新界面
        refresh(list);
        //更新 tf_path
        tf_path.setText(absoluatePath);

        System.out.println("打开目录");
    }



    private void deleteFileMenu(Button button){
        String curPath=tf_path.getText().trim();
        String filename=button.getText();
        String absoluatePath;
        if(curPath.equals("C:/")){
            absoluatePath=curPath+filename;
        }else{
            absoluatePath=curPath+"/"+filename;
        }
        //得到绝对路径 所指向的 行 列
        SearchedFile searchedFile =FileUtil.findPathSearchedFile(DiskFactory.getDisk(),absoluatePath);

        //SearchedFile searchedFile =FileUtil.findFile(absoluatePath,DiskFactory.getDisk());
        //删除
        FileUtil.deleteFileMenu(DiskFactory.getDisk(),searchedFile.getDiskNumber(),searchedFile.getDiskLocation());
        //删除后重新得到当前目录的内容
        List<Item> list=FileUtil.getFileItem(DiskFactory.getDisk(),searchedFile.getDiskNumber());;
        //刷新界面
        refresh(list);

        System.out.println("删除文件/目录");
    }

    private void newLine(){
        if(j==6){
            i++;
            j=0;
        }
    }

    //返回当前磁盘状态
    public String getDiskSpace(){
        return DiskUtil.showDisk(DiskFactory.getDisk());
    }



}

